
//
//  ACPhotoManager.m
//  ACFramework
//
//  Created by caoyq on 2018/6/29.
//

#import "ACPhotoManager.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "SDWebImageDownloader.h"

@interface ACPhotoManager()

/** 图片保存的block */
@property (nonatomic, copy) void(^completionBlock)(NSError *error);

@end

@implementation ACPhotoManager

+ (instancetype)manager
{
    static ACPhotoManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)saveImage: (UIImage *)image completion: (void(^)(NSError *error))completion
{
    self.completionBlock = completion;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)saveImageContainGIF: (UIImage *)image completion: (void(^)(NSError *error))completion
{
    NSData *imgData = UIImageJPEGRepresentation(image, 0.7);
    [self savePhotoContainGIF:imgData completion:completion];
}

- (void)saveImageURLContainGTF: (NSString *)imageURL completion: (void(^)(NSError *error))completion
{
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (error) {
            if (completion) {
                completion(error);
            }
        }else {
            [self savePhotoContainGIF:data completion:completion];
        }
    }];
}

- (void)savePhotoContainGIF: (NSData *)photoData completion: (void(^)(NSError *error))completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if (@available(iOS 9.0, *)) {
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
                options.shouldMoveFile = YES;
                [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:photoData options:options];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(error);
                    }
                });
            }];
        }else {
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeImageDataToSavedPhotosAlbum:photoData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(error);
                    }
                });
            }];
        }
    });
}

#pragma mark - action

///图片保存回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (self.completionBlock) {
        self.completionBlock(error);
    }
}

@end
